package wavenotes.model.image;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

public class ImageFactory {
	public static DatastoreImage createImage(byte[] imageBytes) {
		DatastoreImage image = new DatastoreImage(new Blob(imageBytes));
		
		image.setSmallImage(new Blob(getResizedImage(imageBytes, 300)));
		
		return image;
	}
	
	private static byte[] getResizedImage(byte[] image, int height) {
		ImagesService imagesService = ImagesServiceFactory.getImagesService();

        Image oldImage = ImagesServiceFactory.makeImage(image);
        Transform resize = ImagesServiceFactory.makeResize( (int)((float)height * oldImage.getWidth() / oldImage.getHeight()), height);

        Image newImage = imagesService.applyTransform(resize, oldImage);

        return newImage.getImageData();
	}
}
